package com.bby.disk.util;

import cn.hutool.core.io.FileUtil;
import com.bby.common.exception.BBYException;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class VideoImgUtil {

    public static void main(String[] args) throws BBYException {
        String dir = "C:\\Users\\24686\\Videos\\Captures\\";
        VideoImgUtil.createVideoImg(new File(dir, "QQ录屏20211219201536.mp4"),
                new File(dir, "QQ录屏20211219201536.png"), 7);
    }

    /**
     * 创建视频缩略图
     *
     * @param video  视频文件
     * @param target 存放地址
     * @param offset 偏移帧数,从0开始
     */
    public static void createVideoImg(File video, File target, int offset) throws BBYException {
        try (FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(video)) {
//            avutil.av_log_set_level(avutil.AV_LOG_WARNING);
            frameGrabber.start();
            int ffLength = frameGrabber.getLengthInFrames();
            offset = offset % ffLength;
            int i = 0;
            Frame f = null;
            while (i < ffLength) {
                i++;
                f = frameGrabber.grabImage();
                if ((i > offset) && (f.image != null)) {
                    break;
                }
            }
            if (f == null) {
                return;
            }
            BufferedImage bi = new Java2DFrameConverter().getBufferedImage(f);
            ImageIO.write(bi, FileUtil.getSuffix(target), target);
        } catch (IOException e) {
            throw new BBYException("缩略图创建失败！");
        }
    }

    public static boolean isVideo(String name) {
        return name.toLowerCase().matches("mp4|mov|m4v|m4a|avi");
    }
}
